package com.black.play.listener;

import com.black.play.component.SnakeWindow;
import com.black.play.constant.AppConstant;
import com.black.play.entity.Direction;
import com.black.play.entity.Snake;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 主界面全局监听 snake
 *
 * @author ylx
 */
public class SnakeListener extends KeyAdapter
{
    // 与SnakeWindow持有同一Snake引用
    private final Snake snake;

    public SnakeListener(Snake snake)
    {
        this.snake = snake;
    }

    /**
     * 键盘按键监听
     *
     * @param e 按键事件
     */
    @Override
    public void keyPressed(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        switch (keyCode)
        {
            case KeyEvent.VK_UP:
            case KeyEvent.VK_W:
                snake.changeDirection(Direction.UP);
                break;
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_S:
                snake.changeDirection(Direction.DOWN);
                break;
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_A:
                snake.changeDirection(Direction.LEFT);
                break;
            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_D:
                snake.changeDirection(Direction.RIGHT);
                break;
            case KeyEvent.VK_ESCAPE:
                handleEscape();
                break;
            case KeyEvent.VK_SPACE:
                handleSpace();
                break;
        }
    }

    /**
     * 空格
     * 游戏→暂停
     * 暂停→游戏
     * 菜单→开始
     */
    private void handleSpace()
    {
        SnakeWindow snakeWindow = SnakeWindow.getInstance();
        String activeCard = snakeWindow.getActiveCard();
        switch (activeCard)
        {
            case AppConstant.GAME:
                snakeWindow.pauseGame();
                break;
            case AppConstant.PAUSE:
                snakeWindow.continueGame();
                break;
            case AppConstant.MENU:
                snakeWindow.startGame();
                break;
        }
    }

    /**
     * Esc
     * 菜单→退出
     * 暂停→退出
     * 游戏→暂停
     */
    private void handleEscape()
    {
        SnakeWindow snakeWindow = SnakeWindow.getInstance();
        String activeCard = snakeWindow.getActiveCard();
        switch (activeCard)
        {
            case AppConstant.GAME:
                snakeWindow.pauseGame();
                break;
            case AppConstant.PAUSE:
            case AppConstant.MENU:
                System.exit(0);
                break;
        }
    }
}
